package com.tuanzi.loan.web.bean.member;

import com.tuanzi.loan.business.entity.member.LoanMemberPrice;
import com.tuanzi.loan.business.service.member.LoanMemberPriceService;
import com.tuanzi.loan.core.aspect.Debug;
import com.tuanzi.loan.web.bean.CurrentUserBean;
import com.tuanzi.loan.web.configuration.JSFInfoBean;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.faces.bean.ViewScoped;
import java.util.Objects;

@Data
@Debug
@Component
@ViewScoped
@EqualsAndHashCode(callSuper = true)
public class LoanMemberPriceInfoBean extends JSFInfoBean<LoanMemberPrice>{

    private static final long serialVersionUID = 1766754091552754111L;

    private final LoanMemberPriceService loanMemberPriceService;
    private final CurrentUserBean currentUserBean;

    @Autowired
    public LoanMemberPriceInfoBean(LoanMemberPriceService loanMemberPriceService, CurrentUserBean currentUserBean) {
        this.loanMemberPriceService = loanMemberPriceService;
        this.currentUserBean = currentUserBean;
    }

    @PostConstruct
    private void init(){
        String id = getParamFromRequest("id");
        if(StringUtils.isBlank(id) || !NumberUtils.isNumber(id)){
            $ = new LoanMemberPrice();
            changeStatusToEdit();
        }else {
            $ = loanMemberPriceService.findOne(Long.valueOf(id));
            if(Objects.isNull($)){
                forceRedirect(currentUserBean.getBack());
            }
        }
    }

    public String onReturn(){
        return redirect(currentUserBean.getBack());
    }

    public void onSave(){
        if(StringUtils.isNotBlank($.getProductId())&& null !=$.getPrice()){
            LoanMemberPrice productPriceInfo = loanMemberPriceService.findByProductId($.getProductId());
            if(Objects.nonNull(productPriceInfo)){
                $.setId(productPriceInfo.getId());
            }

            loanMemberPriceService.saveOrUpdate($);
            addSuccessfullyMessage();
            changeStatusToView();
            return;
        }

        addErrorMessage("产品或者价格不能为空");
    }

}
